<template>

<div class="login-background">
  <div class="login-card-container">
    <div class="commonCentent bg" data-theme="light">
      <template v-if="loginType != 'forget'">
        <template v-if="loginType == 'password'">
          <div class="title">密码登录</div>
          <div class="errorMessage">
            <div>{{ errorMsg }}</div>
          </div>
          <div class="mobileInput">
            <el-input suffix-icon="" v-model="loginForm.username" placeholder="请输入手机号" class="commonTabPaneIpt"
                      name="username" maxlength="11"></el-input>
          </div>
          <div class="mobileInput">
            <el-input v-model="loginForm.password" placeholder="请输入密码" :type="see ? 'text' : 'password'"
                      clearable class="commonTabPaneIpt passwordType">
              <template #suffix>
                <i :class="see ? 'see' : 'nosee'" style="margin-top: 8px; font-size: 18px;"
                   @click="toggleSee"></i>
              </template>
            </el-input>

          </div>
        </template>
        <template v-else-if="loginType == 'phone'">
          <div class="title">验证码登录</div>
          <div class="subTitle2" style="text-align: left">未注册用户登录后自动注册</div>
          <div class="errorMessage">
            <div>{{ errorMsg }}</div>
          </div>
          <div class="mobileInput">
            <el-input suffix-icon="" v-model="loginForm.username" placeholder="请输入手机号" class="commonTabPaneIpt"
                      name="username" maxlength="11"></el-input>
          </div>
          <div class="mobileInput">
            <el-input v-model="loginForm.code" placeholder="请输入短信验证码"
                      class="commonTabPaneIpt borderR"></el-input>
            <div class="message_btn" :class="loginForm.username.length == 11 ? 'active' : ''" @click="getCode"
                 v-show="codeTime == 0">获取验证码 </div>
            <div class="message_btn message_btnH" v-show="codeTime != 0">{{ codeTime }}s后重新获取</div>
          </div>
        </template>

          <div class="checkedBox checkedAgreement">
            <el-checkbox v-model="agree" label="我已阅读并同意"></el-checkbox>
            <div><a target="_blank" >《用户服务协议》</a><a
                target="_blank" >《个人信息保护政策》</a></div>
          </div>
          <div style="text-align: center">
            <el-button style="width: 100%" type="primary"  @click="confirmLogin" round  v-loading="loading">
              <span class="login-btn-text">立即登录</span>
            </el-button>
          </div>
          <div class="forgetPassword" v-if="loginType == 'password'" @click="forgetPwd">忘记密码</div>
        <div class="otherType">其他登录方式</div>
        <div class="otherTypeList">
          <!-- <div v-if="loginType != 'sacn'" class="scanIcon" @click="toggle('scan')"></div> -->
          <div v-if="loginType != 'password'" class="passwordIcon" @click="toggle('password')"></div>
          <div v-if="loginType != 'phone'" class="phoneIcon" @click="toggle('phone')"></div>
        </div>
      </template>
      <template v-else>
        <div class="title">{{ title1 }}</div>
        <div class="errorMessage">
          <div>{{ errorMsg }}</div>
        </div>
        <div class="mobileInput">
          <el-input suffix-icon="" v-model="loginForm.username" placeholder="请输入手机号" class="commonTabPaneIpt"
                    name="username" maxlength="11"></el-input>
        </div>
        <div class="mobileInput">
          <el-input v-model="loginForm.code" placeholder="请输入短信验证码" class="commonTabPaneIpt borderR"></el-input>
          <div class="message_btn" :class="loginForm.username.length == 11 ? 'active' : ''" @click="getCode"
               v-show="codeTime == 0">获取验证码 </div>
          <div class="message_btn message_btnH" v-show="codeTime != 0">{{ codeTime }}s后重新获取</div>
        </div>
        <div class="mobileInput">
          <el-input v-model="loginForm.password" placeholder="8-20位密码，字母、数字、符号至少2种组合"
                    :type="see ? 'text' : 'password'" clearable class="commonTabPaneIpt passwordType" minlength="8"
                    maxlength="20">
            <template #suffix>
              <i :class="see ? 'see' : 'nosee'" style="margin-top: 8px; font-size: 18px;"
                 @click="toggleSee"></i>
            </template>
          </el-input>
        </div>
        <div class="mobileInput">
          <el-input v-model="loginForm.passwordAgain" placeholder="确认您的密码" :type="see ? 'text' : 'password'"
                    clearable class="commonTabPaneIpt passwordType" minlength="8" maxlength="20">
            <template #suffix>
              <i :class="see ? 'see' : 'nosee'" style="margin-top: 8px; font-size: 18px;"
                 @click="toggleSee"></i>
            </template>
          </el-input>
        </div>
        <div style="text-align: center">
          <el-button type="primary" style="width: 100%" @click="resetPwdOrRegister" round>
            <span class="login-btn-text">确定</span>
          </el-button>
        </div>


        <div style="text-align: center">
          <div class="phoneIcon" @click="toggle('phone')"></div>

        </div>

      </template>
    </div>
  </div>
</div>

</template>
<script setup>
import homeApis from '@/apis/home.js'
import QRCode from 'qrcode'
import { nextTick } from 'vue';
import Cookies from 'js-cookie';
import useUserStore from '@/stores/user.js'

import {ElMessage, ElMessageBox} from 'element-plus'
import config from '@/config/index.js'
import {setToken, setUserIdInCookie} from '@/utils/token.js'
import useCookieStorage from '@/stores/cookieStorage.js'

const emits = defineEmits(['closeAlertIcon', 'update:title1'])


const title1='设置新登录密码'
const titles=['设置新登录密码', '注册'];
const cookieStorage=useCookieStorage()

const router = useRouter();
const userStore = useUserStore()

onMounted(() => {

})
// deviceType根据后端枚举类型
let deviceType = 0
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

if (isMobile) {
  // deviceType = 4
  deviceType = "pc"
} else {
  // deviceType = 3
  deviceType = "pc"
}



const dialog = ref(null)
const loginType = ref('password')//scan,password,phone,forget
const loginForm = reactive({
  username: '',
  // username: '16999999999',
  code: '',
  password: '',
  // password: 'tk123456',
  passwordAgain: ''
})
const errorTips = ['手机号码格式不正确', '验证码不能为空', '密码不能为空', '密码格式不正确', '两次密码不一致']
const errorMsg = ref('')
const showProtocolWarn = ref(false)
const agree = ref(false)
const loginFlag = ref(false)
const codeTime = ref(0)
const see = ref(false)
const loginQrCode = ref(null)
let intervalId = null
const refreshQrFlag = ref(false)
const canClick = ref(false)
const loading=ref(false)
const codeType = computed(() => {
  if (loginType.value == 'forget') {
    if (title1 == titles[0]) return 'forgetPass';
    else return 'register';

  } else {
    return 'login'
  }
})

watch([loginType, loginForm], ([n1, n2], [o1, o2]) => {
  if (n1 == 'scan' && (o1 == undefined || n1 != o1)) {
    nextTick(() => {
      initAndRefreshQrCode()
    })
  } else {
    clearInterval(intervalId)
  }

  if (n2 && o2) {

    if (loginType.value == 'forget' || loginType.value == 'phone') {
      if (n2.username.trim().length != 11) {
        if (errorMsg.value == '') {
          errorMsg.value = errorTips[0];
        }
      } else {
        errorMsg.value = ''
      }
    }



    let f = true
    Object.values(n2).forEach(e => {
      if (e.trim().length == 0) f = false
    })
    if (f) {
      canClick.value = true
    } else {
      canClick.value = false
    }

  }




}, { immediate: true, deep: true })

function refreshQr() {
  refreshQrFlag.value = false
  initAndRefreshQrCode()
}
function closeAlertIcon() {
  errorMsg.value = ''
  clearInterval(intervalId)
  emits('closeAlertIcon', true)
}
function toggle(type) {
  loginType.value = type
  loginForm.code='';
  loginForm.passwordAgain='';
}
async function initLoginQrCode() {

  const res = await homeApis.initLoginQrCode()
  loginQrCode.value = res.entity
  // QRCode.toCanvas(document.getElementById('qrcode'), res.entity.qrCodeContent, {
  //     width: 140,
  //     height: 140,
  //     color: {
  //         dark: '#000000', // 黑色
  //         light: '#ffffff' // 白色
  //     }
  // }, function (error) {
  //     if (error) console.error(error);
  //     console.log('QR code generated successfully!');
  // });
  QRCode.toCanvas(document.getElementById('qrcode1'), res.entity.qrCodeContent, {
    width: 140,
    height: 140,
    color: {
      dark: '#000000', // 黑色
      light: '#ffffff' // 白色
    }
  }, function (error) {
    if (error) console.error(error);
    console.log('QR code generated successfully!');
  });
}
function getLoginQrCodeStatus() {
  return homeApis.getLoginQrCodeStatus()
}
function initAndRefreshQrCode() {
  initLoginQrCode()
  // 2s
  intervalId = setInterval(async () => {
    const res = await getLoginQrCodeStatus()
    if (res.entity.status != 0) {
      refreshQrFlag.value = true;
      clearInterval(intervalId)
    }
    // if (res.entity.status == 0) {
    //     refreshQrFlag.value=true;
    //     clearInterval(intervalId)
    // }
  }, 2000)
}

function forgetPwd() {
  loginType.value = 'forget'
  emits('update:title1', titles[0])

}
function toggleSee() {
  see.value = !see.value
}
function getCode() {
  if (codeTime.value != 0) return;
  codeTime.value = 60;
  if (loginForm.username.trim().length != 11) return;
  homeApis.phone_code({
    phone: loginForm.username,
    smsCodeType: codeType.value,

  }).then(res => {
    let id = setInterval(() => {
      codeTime.value--
      if (codeTime.value == 0) {
        clearInterval(id)
      }
    }, 1000)
  })

}
function cancel() {
  showProtocolWarn.value = false
}
function agreeAndLogin() {
  agree.value = true;
  cancel();
  confirmLogin()
}
function resetPwdOrRegister() {

  if (loginFlag.value) return;
  if (errorMsg.value != '') return;

  if (loginForm.username.trim().length != 11) {
    errorMsg.value = errorTips[0]
  }
  const reg = /(?!^\d+$)(?!^[A-Za-z]+$)(?!^[^A-Za-z0-9]+$)(?!^.*[\u4E00-\u9FA5].*$)^\S{8,20}$/
  if (!reg.test(loginForm.password)) {

    errorMsg.value = errorTips[3]
  }
  if (loginForm.password != loginForm.passwordAgain) {
    errorMsg.value = errorTips[4]
  }
  if (loginForm.code.trim().length == 0) {
    errorMsg.value = errorTips[1]
  }
  if (errorMsg.value != '') return;

  if (loginType.value == 'forget' && title1 == titles[1]) {
    loginFlag.value = true
    // 注册
    homeApis.login({
      deviceType: deviceType,
      userAccount: loginForm.username,
      code: loginForm.code,
      credential: loginForm.password,
      type: 4
    }).then(res => {
      //   获取其选中的考试科目，没选中则重新选择，强制用户选择

      // return
      // homeApis.login({
      //
      // }).then(res => {
      //   let userId = res.data.userId;
      //   // 获取个人信息
      //   Cookies.set('userId', userId, { expires: 7 })
      //   userStore.setUserId(userId)
      //   emits('closeAlertIcon', true)
      //   cookieStorage.setIsLogin(true)
      //
      //
      //
      //
      // })
    }).finally(() => {
      loginFlag.value = false
    })
  } else {
    // 设置新密码
    // homeApis.retrievePassword(loginForm).then(res => {

    // })


    homeApis.forget_pass({
      userAccount: loginForm.username,
      code: loginForm.code,
      credential: loginForm.password,
    }).then(res => {
      ElMessage({
        message: '密码重置成功，请重新登录',
        type: 'success',
        duration: 2000,
      })
      emits('closeAlertIcon', true)
      // 清除cookie

      // homeApis.logout().then(res => {
      //     // 登出
      //     local.setIsLogin(false)
      //     local.removeToken()
      //     emits('closeAlertIcon', true)
      //     ElMessage({
      //         message: '密码重置成功，请重新登录',
      //         type: 'success',
      //         duration: 2000,

      //     })
      // }).cathc(e => {

      // })
    })
  }


}
function confirmLogin() {
  // console.log(loginType.value)
  // return
  if (loginFlag.value) return;
  if (!agree.value) {
    // showProtocolWarn.value = true
    ElMessageBox.alert('您未同意用户协议',{
      title: '提示',
      message: '您未同意用户协议',
      confirmButtonText: '同意',
      type: 'warning',
      center: true,
    }).then(() => {
      agree.value=true;
    }).catch(() => {
      // onCancel
    });
    return;
  }

  // 校验
  //
  let promiseRes = null;
  loginFlag.value = true;

  if (loginType.value == 'password') {

    promiseRes = homeApis.login({
      deviceType,
      type: 0,
      userAccount: loginForm.username,
      // sm2Encrypt(loginForm.password, config.loginPubkey, 0)
      credential: loginForm.password,

      // userType:2
    })
    // 验证码登录
  } else if (loginType.value == 'phone') {
    promiseRes = homeApis.login({
      userAccount: loginForm.username,
      code: loginForm.code,
      deviceType,
      type: 1,
    },{
      headers:{
        Dt:"pc"
      }
    })
  }
  loading.value = true;
  promiseRes.then(res => {
    if (res.code == 1) {
      router.push('/initSelect')
      let now =new Date()
      const userId = res.data.id
      cookieStorage.setIsLogin(true)
      cookieStorage.setUserId(userId)
      setUserIdInCookie(userId)


      userStore.setUserInfo(res.data)
      userStore.setTime(now.getTime())
      setToken(res.data.token)
    }
  }).finally(() => {
    loginFlag.value = false
    loading.value = false;
  })



}


defineExpose({
  loginType
})

</script>

<style scoped>
.login-background{
  height: 700px;
  background-image: url('@/assets/images/background2.png');
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-card-container{
  background: white;
  border-radius: 10px;
  box-sizing: border-box;
  padding: 0px 49px;
  width: 468px;
  height: 490px;
  display: flex;
  flex-direction: column;
  align-items: center;
}




.commonCentent.bg {
  background-image: var(--bg);
  background-repeat: no-repeat;
  background-size: 100% auto;
  background-position: 0 100%;
}

.commonCentent {
  padding: 30px;
  width: 400px;
  min-height: 400px;
  background: var(--bg_white);
  border-radius: 10px;
}

.commonCentent .closeAlertIcon {
  width: 24px;
  height: 24px;
  background: var(--closeIcon) no-repeat;
  background-size: 100%;
  position: absolute;
  right: 10px;
  top: 10px;
  cursor: pointer;
  transition: transform .2s;
}

.scanTitle {
  width: 100%;
  text-align: center;
  line-height: 28px;
  font-size: 20px;
  color: var(--gray_0);
  margin-top: 50px;
  font-weight: 400;
}

.scanTitle .colorText {
  margin: 0 2px;
  font-weight: 600;
  background: linear-gradient(90.23deg, #05c9c2 15.81%, #0c7de4 84.91%, #7d45f4 104.38%);
  /* -webkit-background-clip: text;
  -webkit-text-fill-color: transparent; */
}

.subTitle2,
.subTitle {
  color: var(--gray_70);
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 12px;
  line-height: 16px;
  width: 100%;
  margin: 10px 0 30px;
  text-align: center;
}

.scanContainer {
  margin: 0 auto 59px;
  padding: 8px;
  width: 158px;
  height: 158px;
  border-radius: 5px;
  border: 1px solid var(--gray_93);
  box-sizing: border-box;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.commonCentent .otherType {
  margin-top: 16px;
  width: 100%;
  text-align: center;
  color: var(--gray_70);
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 12px;
  line-height: 16px;
}

.commonCentent .otherTypeList {
  width: 100%;
  display: flex;
  margin-top: 15px;
  justify-content: space-evenly;
  align-items: center;
  box-sizing: border-box;
}

.commonCentent .otherTypeList div {
  width: 40px;
  height: 40px;
  background-size: 100%;
  cursor: pointer;
}

.commonCentent .otherTypeList .passwordIcon {
  background-image: var(--passwordIcon);
}

.commonCentent .otherTypeList .scanIcon {
  background-image: var(--QrcodeIcon);
}

.commonCentent .otherTypeList div {
  width: 40px;
  height: 40px;
  background-size: 100%;
  cursor: pointer;
}

.phoneIcon {
  background-image: var(--phoneIcon);
  width: 40px;
  height: 40px;
  background-size: 100%;
  display: inline-block;
}

.commonCentent .title {
  color: var(--gray_0);
  font-family: PingFang SC;
  font-weight: 500;
  font-size: 24px;
  line-height: 34px;
}

.commonCentent .errorMessage {
  width: 100%;
  height: 30px;
  padding-top: 12px;
  padding-bottom: 2px;
}

.commonCentent .mobileInput {
  margin-bottom: 15px;
  width: 100%;
  height: 40px;
  display: flex;
}

.commonCentent .mobileInput .commonTabPaneIpt {
  flex: 1;
}

.commonCentent .mobileInput .commonTabPaneIpt {
  flex: 1;
}

.commonCentent .checkedAgreement {
  margin-top: 10px;
  width: auto;
}

.commonCentent .checkedBox {
  border-color: var(--gray_80);
  font-size: 12px;
  width: 350px;
  line-height: 17px;
  display: flex;
}

.commonCentent .checkedAgreement div {
  display: flex;
  align-items: center;
}

.commonCentent .checkedAgreement a {
  color: var(--blue_n);
}

.commonCentent .commonBtn {
  margin-bottom: 42px;
  width: 100%;
  height: 40px;
  border-radius: 20px;
  background: var(--gray_97);
  margin-top: 20px;
  text-align: center;
  line-height: 40px;
  font-size: 14px;
  color: var(--gray_80);
  cursor: pointer;
}

.commonCentent .forgetPassword {
  text-align: right;
  color: var(--gray_35);
  font-weight: 400;
  font-size: 12px;
  line-height: 16px;
  width: 100%;
  margin: 10px 0 37px;
  cursor: pointer;
}

.nosee {
  cursor: pointer;
  display: inline-block;
  background-image: var(--closeSee);
  width: 24px;
  height: 24px;
  background-size: 100%;
}

.see {
  cursor: pointer;
  display: inline-block;
  background-image: var(--see);
  width: 24px;
  height: 24px;
  background-size: 100%;
}

.commonCentent .mobileInput .message_btn {
  height: 100%;
  width: 90px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0 3px 3px 0;
  background: var(--gray_97);
  color: var(--gray_80);
  font-weight: 400;
  font-size: 14px;
  border-top: 1px solid var(--gray_85);
  border-bottom: 1px solid var(--gray_85);
  border-right: 1px solid var(--gray_85);
}

.commonCentent .mobileInput .message_btnH {
  width: 114px;
  cursor: default;
}

.commonCentent .mobileInput .message_btn.active {
  cursor: pointer;
  color: var(--blue_n);
}

.commonCentent .commonBtn.active {
  background: var(--green_n);
  color: #fff;
}

.commonCentent .errorMessage div {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  color: #ff5840;
  font-weight: 400;
  font-size: 12px;
  line-height: 1;
}

.checkedAgreement :deep(.el-checkbox__label) {
  font-size: 12px;
}


.messageDialogMask .messageDialog {
  width: 340px;
  background: var(--bg_white);
  border-radius: 10px;
  flex-direction: column;
  position: relative;
}

.messageDialogMask .messageDialog,
.messageDialogMask {

  display: flex;
  justify-content: center;
  align-items: center;
}

.messageDialogMask .messageDialog .closeIcon {
  position: absolute;
  top: 13px;
  right: 10px;
  width: 24px;
  height: 24px;
  background: var(--closeIcon) no-repeat;
  background-size: 100%;
  cursor: pointer;
  transition: transform .2s;
}

.messageDialogMask .messageDialog .title {
  text-align: center;
  width: 100%;
  color: var(--gray_20);
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  padding: 13px 0;
  border-bottom: 1px solid var(--gray_93);
}

.messageDialogMask .messageDialog .agreement {
  padding: 30px;
  text-align: center;
  color: var(--gray_20);
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 14px;
  line-height: 20px;
}

.messageDialogMask .messageDialog .agreement a {
  color: var(--blue_n);
}

.messageDialogMask .messageDialog .buttonList {
  padding: 0 40px 32px;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
}

.messageDialogMask .messageDialog .buttonList div {
  width: 120px;
  text-align: center;
  padding: 10px 0;
  border-radius: 20px;
  background: var(--gray_97);
  color: var(--gray_50);
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 14px;
  line-height: 20px;
  cursor: pointer;
}

.messageDialogMask .messageDialog .buttonList div:last-child {
  background: var(--green_n);
  color: var(--on_surface);
}

.messageDialogMask .messageDialog .buttonList div {
  width: 120px;
  text-align: center;
  padding: 10px 0;
  border-radius: 20px;
  background: var(--gray_97);
  color: var(--gray_50);
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 14px;
  line-height: 20px;
  cursor: pointer;
}

.scanContainer .refresh {
  cursor: pointer;
  position: absolute;
  padding-bottom: 36px;
  width: 142px;
  height: 142px;
  background: hsla(0, 0%, 100%, .98);
  color: var(--gray_20);
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 12px;
  line-height: 16px;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: flex-end;
  overflow: hidden;
}

.scanContainer .refresh .refreshIcon {
  margin-bottom: 10px;
  width: 44px;
  height: 44px;
  background-size: 100%;
  background-image: var(--refreshIcon);
}
.login-btn-text{
  padding: 0 16px;
}
</style>
